package com.pig4cloud.pigx.gateway;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.*;
import io.netty.util.CharsetUtil;

/**
 * http 请求处理器
 * 2018/11/1.
 */
public class HttpRequestHandler extends SimpleChannelInboundHandler<FullHttpRequest> {


    private final StringBuilder contentBuffer = new StringBuilder();

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest request) throws Exception {

        if (request.method().toString().equals("GET")) {
            QueryStringDecoder decoder = new QueryStringDecoder(request.uri());
            decoder.parameters().forEach((name, values) -> {
                System.out.println("Parameter: " + name + " = " + values);
            });
        } else {
            // 如果是POST请求，等待完整的请求内容
            request.content().retain(); // 防止释放资源，避免内存泄漏
            request.content().writeBytes(contentBuffer.toString().getBytes());
            contentBuffer.setLength(0); // 清空缓冲区

            ByteBuf content = request.content();
            if (content.isReadable()) {
                contentBuffer.append(content.toString(CharsetUtil.UTF_8));
            }
            // 最后一部分请求内容已接收完毕，解析参数
            String requestBody = contentBuffer.toString();
            System.out.println("Received JSON POST request body: " + requestBody);

        }

        // 处理HTTP请求
        String content = "Hello, World!";

        DefaultFullHttpResponse response = new DefaultFullHttpResponse(
                HttpVersion.HTTP_1_1,
                HttpResponseStatus.OK,
                Unpooled.wrappedBuffer(content.getBytes()));

        response.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/plain");
        response.headers().set(HttpHeaderNames.CONTENT_LENGTH, response.content().readableBytes());
        response.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE);

        ctx.writeAndFlush(response);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }
}
